package com.yj.mvc.web.servlet.resource;

import cn.hutool.core.util.StrUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.Iterator;

public class XmlResource implements Resource {
    
    private String path;

    private Document document;
    
    private Element rootElement;
    
    private Iterator iterator;
    
    
    public XmlResource(String path) {
        this.path = path;
        parse(path);
    }

    private void parse(String path) {
        if (StrUtil.isBlank(path)){
            throw new IllegalArgumentException("path cannot be blank");
        }

        URL resource = this.getClass().getClassLoader().getResource(path);
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(resource);
            rootElement = document.getRootElement();
            iterator = rootElement.elementIterator();
        }catch (Exception e){
            throw new IllegalArgumentException("parse xml error", e);
        }
    }


    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public Object next() {
        return iterator.next();
    }
}
